import time

from django.shortcuts import get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User

from brispon.util.decorators import render_to, ajax_request, json_response
from brispon.util import BaseSearchForm, paginate, inc_paginate
from brispon.models import Coupon, info
from brispon.util.sms import send

class CouponForm(BaseSearchForm):
    class Meta:
        base_qs = Coupon.objects
        search_fields = ('name',) 
        default_fields = {}

@render_to('d/coupon/list.html')
def list(request):
    if request.is_mobile:
        return redirect('brispon.views.coupon.mlist')
    coupon_form = CouponForm(request.GET or None)
    coupons = Coupon.objects.get_acoupon()
    return paginate(request.GET, search_form=coupon_form, objects=coupons, unit_page=15)


@json_response
def send_sms(request, coupon_id, user_id):
    result = {'success': True,
              'msg': ''
              }
#    if not request.user.is_authenticated():# or request.user.is_anonymous():
#        result['success'] = False
#        result['msg'] = '111'
#        return {'result': result}
    
#    if request.user.is_anonymous():
#        result['success'] = False
#        result['msg'] = '222'
#        return {'result': result}
    try:
        user = User.objects.get(pk=int(user_id))
        coupon = get_object_or_404(Coupon, pk=coupon_id)
        success, msg = coupon.send_coupon_by_sms(user)
        result['success'] = success
        result['msg'] = msg
        info('SENDING SMS result-success: %s, msg: %s' % (success, msg))
    except:
        result['success'] = False
        result['msg'] = 'Something went wrong'
    return {'result':result}

@render_to('m/coupon/list.html')
def mlist(request):
    if not request.is_mobile:
        return redirect('brispon.views.coupon.list')
    coupon_form = CouponForm(request.GET or None)
    return paginate(request.GET, search_form=coupon_form, unit_page=12)

@render_to('d/coupon/detail.html')
def detail(request, coupon_id):
    coupon = get_object_or_404(Coupon, pk=coupon_id)
    return {'coupon':coupon}

@render_to('m/coupon/detail.html')
def mdetail(request, coupon_id):
    coupon = get_object_or_404(Coupon, pk=coupon_id)
    return {'coupon':coupon}
